﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ZHJ.PerfectOA.Common;
using ZHJ.PerfectOA.Model;

namespace ZHJ.PerfectOA.WebApp.Controllers
{
    public class LoginController : Controller
    {
        //
        // GET: /Login/

        IBLL.IUserInfoService UserInfoService { get; set; }
        public ActionResult Index()
        {
            //检验是否有cookie自动登录
            CheckCookieInfo();
            return View();
        }

        #region ccokes登录
        /// <summary>
        /// cookie登录
        /// </summary>
        private void CheckCookieInfo()
        {
            if (Request.Cookies["cp1"] != null && Request.Cookies["cp2"] != null)
            {
                string userName = Request.Cookies["cp1"].Value;
                string userPwd = Request.Cookies["cp2"].Value;
                //先判断用户名是否存在
                UserInfo userinfo = UserInfoService.LoadEntities(u => u.UName == userName).FirstOrDefault();
                if (userinfo != null)
                {
                    //判断密码是否错误
                    if (userPwd == WebCommon.GetMd5String(WebCommon.GetMd5String(userinfo.UPwd)))
                    {
                        //模仿session操作
                        string sessionId = Guid.NewGuid().ToString();
                        Common.MemcacheHelper.Set(sessionId, Common.SerializeHelper.SerializeToString(userinfo), DateTime.Now.AddMinutes(20));
                        Response.Cookies["sessionId"].Value = sessionId;
                        Response.Redirect("/Home/Index");
                    }
                }
                Response.Cookies["cp1"].Expires = DateTime.Now.AddDays(-1);
                Response.Cookies["cp2"].Expires = DateTime.Now.AddDays(-1);
            }
        }
        #endregion

        #region 展示验证码
        /// <summary>
        /// 展示验证码
        /// </summary>
        /// <returns></returns>
        public ActionResult ShowValidateCode()
        {
            Common.ValidateCode vCode = new Common.ValidateCode();
            string codeStr = vCode.CreateValidateCode(4);
            Session["vCode"] = codeStr;
            byte[] buffer = vCode.CreateValidateGraphic(codeStr);
            return File(buffer, "image/jpeg");
        }
        #endregion

        #region 登陆方法
        public ActionResult UserLogin()
        {
            //判断验证码是否为空
            string vcode = Session["vCode"] == null ? string.Empty : Session["vCode"].ToString();
            if (vcode == null)
            {
                return Content("no:验证码错误!");
            }
            //将session清空，如果不清空会有安全隐患
            Session["vCode"] = null;
            string cilentVCode = Request["vCode"];
            if (!vcode.Equals(cilentVCode, StringComparison.InvariantCultureIgnoreCase))
            {
                return Content("no:验证码错误!");
            }
            string name = Request["LoginCode"];
            string pwd = Request["LoginPwd"];
            //var userInfo = UserInfoService.LoadEntities(u => u.UName == name && u.UPwd == pwd).FirstOrDefault();
            var userInfo = UserInfoService.LoadEntities(u => u.UName == name && u.UPwd == pwd).FirstOrDefault();
            if (userInfo != null)
            {
                //模拟Session的登陆状态保持
                //创建一个相当于一个SessionID的string
                string sessionId = Guid.NewGuid().ToString();
                //将sessionID作为Key和序列化之后的登陆成功的对象作为Value存到Memcached中
                Common.MemcacheHelper.Set(sessionId, Common.SerializeHelper.SerializeToString(userInfo), DateTime.Now.AddMinutes(20));
                //将sessionID发到客户端的cookies中
                Response.Cookies["sessionId"].Value = sessionId;
                //如果用户选择了记住我的功能 设置cookie发送客户端
                if (!string.IsNullOrEmpty(Request["checkMe"]))
                {
                    HttpCookie cookie1 = new HttpCookie("cp1", userInfo.UName);
                    HttpCookie cookie2 = new HttpCookie("cp2", WebCommon.GetMd5String(WebCommon.GetMd5String(userInfo.UPwd)));
                    cookie1.Expires = DateTime.Now.AddDays(3);
                    cookie2.Expires = DateTime.Now.AddDays(3);
                    Response.Cookies.Add(cookie1);
                    Response.Cookies.Add(cookie2);
                }
                return Content("ok:登陆成功");
            }
            else
            {
                return Content("no:登陆失败");
            }
        }

        #endregion

        #region 退出登录
        /// <summary>
        /// 退出登录
        /// </summary>
        /// <returns></returns>
        public ActionResult LoginOut()
        {
            //拿到sessionID的值，也就是Memcache中的键
            if (Request.Cookies["sessionId"] != null)
            {
                //销毁Memcache中键值对
                Common.MemcacheHelper.Delete(Request.Cookies["sessionId"].Value);
                //将cookie设置过期
                Response.Cookies["cp1"].Expires = DateTime.Now.AddDays(-1);
                Response.Cookies["cp2"].Expires = DateTime.Now.AddDays(-1);
            }
            return Redirect("/Login/Index");
        }
        #endregion
    }
}
